import socket
import threading


def clinentReq(severClientSocket, ipPort):
    print(ipPort)
    while True:
        recvData = severClientSocket.recv(1024)
        if recvData:
            recvDataLen = len(recvData)
            print("接收数据长度为：", recvDataLen)
            recvConetnt = recvData.decode("gbk")
            print("客服端接收数据为：", recvConetnt)
            sendData = "接收到了....".encode("gbk")
            severClientSocket.send(sendData)
        else:
            print(ipPort, "退出连接！")
            break

    severClientSocket.close()


if __name__ == "__main__":
    tcpSeverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置端口复用，让程序退出释放端口
    tcpSeverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 绑定端口号
    tcpSeverSocket.bind(("", 9090))
    # 设置监听，最大连接128
    tcpSeverSocket.listen(128)
    # 等待客户端建立连接的请求, 只有客户端和服务端建立连接成功代码才会解阻塞，代码才能继续往下执行
    # 1. 专门和客户端通信的套接字： service_client_socket
    # 2. 客户端的ip地址和端口号： ip_port
    while True:
        print("8888888888888888")
        severClientSocket, ipPort = tcpSeverSocket.accept()
        subThread = threading.Thread(
            target=clinentReq, args=(severClientSocket, ipPort)
        )
        subThread.setDaemon(True)
        subThread.start()
    tcpSeverSocket.close()
